package com.atguigu.day04;

import com.atguigu.util.IntSource;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.scala.typeutils.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Comparator;

/**
 * @description :
 * @autor :lyh
 */
public class Example2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntSource())
                .keyBy(r -> r % 2)
                .process(new HistoryDataSource())
                .print();

        env.execute();
    }

    public static class HistoryDataSource extends KeyedProcessFunction<Integer, Integer, String> {

        private ListState<Integer> historyData;

        @Override
        public void open(Configuration parameters) throws Exception {
            historyData = getRuntimeContext().getListState(
                    new ListStateDescriptor<Integer>(
                            "history-data",
                            Types.INT()
                    )
            );
        }

        @Override
        public void processElement(Integer in, KeyedProcessFunction<Integer, Integer, String>.Context ctx, Collector<String> out) throws Exception {
            historyData.add(in);

            // 将列表状态变量中的数据取出，并放在ArrayList中排序
            ArrayList<Integer> integers = new ArrayList<>();
            for (Integer i : historyData.get()) integers.add(i);

            // 升序排序
            integers.sort(new Comparator<Integer>() {
                @Override
                public int compare(Integer o1, Integer o2) {
                    return o1 - o2;
                }
            });

            StringBuilder result = new StringBuilder();
            if (ctx.getCurrentKey() == 0) {
                result.append("偶数历史排序：");
            } else {
                result.append("奇数历史排序：");
            }

            for (Integer i : integers) {
                result.append(i + " => ");
            }

            out.collect(result.toString());
        }
    }
}
